﻿<%@ WebHandler Language="C#" Class="MfgorderTouLiaoInfoDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;
using System.Collections;

/**
 * Description: 订单投料完成率看板
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.10.14
 */

public class MfgorderTouLiaoInfoDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getChartDetail":
                        r = getChartDetail(jObject);//查询柱状图明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getContainerDetail":
                        r = getContainerDetail(jObject);//查询批次明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getDataSql(JObject jObject)
    {
        string sql = @"
SELECT t.factoryname,t.mfgordername,t.mfgqty,t.productname,t.plandate,
       CASE WHEN SUM(t.daoliaoqty) >= t.mfgqty THEN '已到料' ELSE '未到料' END status,
       CASE WHEN SUM(t.daoliaoqty) >= t.mfgqty THEN MAX(t.materialdate) ELSE NULL END materialdate,
       CASE WHEN SUM(t.daoliaoqty) >= t.mfgqty THEN t.mfgqty ELSE SUM(t.daoliaoqty) END daoliaoqty,
       CASE WHEN t.mfgqty - SUM(t.daoliaoqty) < 0 THEN 0 ELSE t.mfgqty - SUM(t.daoliaoqty) END queliaoqty
FROM 
(
  SELECT f.factoryname,t.mfgordername,t.mfgqty,t.productname,t.plannedstartdate - 1 plandate,
         t.containername,
         t.originalqty,
         t.scrapqty,
         t.qty,
         CASE WHEN t.isinstore = -1 AND t.materialdate IS NULL THEN '未到料' ELSE '已到料' END status,
         CASE WHEN t.isinstore = -1 AND t.materialdate IS NULL THEN 0 ELSE (CASE WHEN t.originalqty >= t.mfgqty THEN t.mfgqty ELSE t.originalqty END) END daoliaoqty,
         t.materialdate
  FROM r_mfgordertouliaoboard t
  LEFT JOIN mes_factory_mapping@insitedb74 f ON f.factorycode = t.factorycode
  WHERE t.factorycode IN ('601','609','600','607','608') AND TRUNC(t.plannedstartdate - 1) >= to_date('{0}','yyyy/mm/dd') AND TRUNC(t.plannedstartdate - 1) <= to_date('{1}','yyyy/mm/dd')
";
        JArray selectdate = JArray.Parse(jObject["selectdate"].ToString());
        sql = string.Format(sql, selectdate[0].ToString(), selectdate[1].ToString());

        if (jObject["factoryname"] != null)
        {
            sql += string.Format(" AND t.factoryname = '{0}'", jObject["factoryname"].ToString());
        }
        sql += @"
) t
";

        if (jObject["seriesName"] != null)
        {
            if (jObject["seriesName"].ToString() == "已到料")
            {
                sql += " HAVING SUM(t.daoliaoqty) >= t.mfgqty ";
            }

            if (jObject["seriesName"].ToString() == "未到料")
            {
                sql += " HAVING SUM(t.daoliaoqty) < t.mfgqty ";
            }
        }

        sql += "GROUP BY t.factoryname,t.mfgordername,t.mfgqty,t.productname,t.plandate";
        return sql;
    }

    Result getData(JObject jObject)
    {
        string sql = @"
SELECT t.factoryname,COUNT(1) total,
       SUM(decode(t.status,'已到料',1,0)) ydl,
       SUM(decode(t.status,'未到料',1,0)) wdl,
       CASE WHEN COUNT(1) = 0 THEN 0 ELSE ROUND(SUM(decode(t.status,'已到料',1,0)) / COUNT(1),4) * 100 END ydlRate,--已到料率
       CASE WHEN COUNT(1) = 0 THEN 0 ELSE ROUND(SUM(decode(t.status,'未到料',1,0)) / COUNT(1),4) * 100 END wdlRate --未到料率
FROM (
    {0}
) t
GROUP BY t.factoryname
";
        sql = string.Format(sql, getDataSql(jObject));

        DataTable dtResult = dal.GetDataTable(sql, "MESDB17");
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //订单投料明细
    Result getChartDetail(JObject jObject)
    {
        string sql = getDataSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"], "MESDB17");
        DataTable dtResult = dto.DBTable;

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //订单各批次明细
    Result getContainerDetail(JObject jObject)
    {
        string sql = @"
SELECT f.factoryname,t.mfgordername,t.mfgqty,t.productname,t.containername,t.qty,t.scrapqty,
       t.plannedstartdate - 1 plandate,
       cci.workflowstepname,
       CASE WHEN t.isinstore = -1 AND t.materialdate IS NULL THEN '未到料' ELSE '已到料' END status,
       CASE WHEN t.isinstore = -1 AND t.materialdate IS NULL THEN 0 ELSE (CASE WHEN t.originalqty >= t.mfgqty THEN t.mfgqty ELSE t.originalqty END) END faliaoqty,
       t.materialdate
FROM r_mfgordertouliaoboard t
LEFT JOIN containercurrentinfo@insitedb74 cci ON cci.containername = t.containername
LEFT JOIN mes_factory_mapping@insitedb74 f ON f.factorycode = t.factorycode
WHERE t.mfgordername = '{0}'
";
        sql = string.Format(sql, jObject["mfgordername"].ToString());
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"], "MESDB17");
        DataTable dtResult = dto.DBTable;

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getDataSql(jObject);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dtResult.Columns["factoryname"].Caption = "分厂";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["mfgqty"].Caption = "订单数量";
        dtResult.Columns["productname"].Caption = "件号";
        dtResult.Columns["plandate"].Caption = "计划到料时间";
        dtResult.Columns["materialdate"].Caption = "实际到料时间";
        dtResult.Columns["daoliaoqty"].Caption = "到料数";
        dtResult.Columns["queliaoqty"].Caption = "缺料数";
        dtResult.Columns["status"].Caption = "状态";
        ExportHelper.ExportExcel(dtResult, "订单投料完成率看板导出数据");
    }
}